import org.apache.poi.hwpf.HWPFDocument
import org.apache.poi.hwpf.usermodel.Range
import com.alibaba.fastjson.JSON

def dir = new File("E:/tmp/办事服务99项");
dir.eachFile {f ->
    if (f.isDirectory()) {
        f.eachFile {ff ->
            if (ff.getName().endsWith(".docx")) {
                println "start process file: $ff.name";
                def fff = new File(f, ff.getName().replace(".docx", ".json"));
                fff.exists() ? fff.delete() : fff.createNewFile()
                if (fff.exists()) fff << docx(ff)
            }
            else if (ff.getName().endsWith(".doc")) {
                println "start process file: $ff.name";
                def fff = new File(f, ff.getName().replace(".doc", ".json"));
                fff.exists() ? fff.delete() : fff.createNewFile()
                if (fff.exists()) fff << doc(ff)
            }
        }
    }
}


//def filePath = "E:/tmp/22.doc"
//if (filePath.endsWith("doc")) doc(new File(filePath))
//else docx()


import org.apache.poi.hwpf.usermodel.TableIterator
// 2003 doc word 文档
def doc(file) {
    HWPFDocument doc = null;
    try {
        doc = new HWPFDocument(new FileInputStream(file));
        Range r = doc.getRange();
        TableIterator it = new TableIterator(r);
        if (!it.hasNext()) return ""
        def tb = it.next();
        def data = [];
        (0..tb.numRows()-1).each {i ->
            def row = tb.getRow(i);
            data << [
                    title: row.getCell(0).text().replace("\r", "").replace("\u0007", ""),
                    content: row.getCell(1).text().replace("\r", "</br>").replace("\u0007", "")
            ]
        }
        return JSON.toJSONString([data: data])
    } catch (ex) {
        log.error(ex);
    } finally {
        doc?.close();
    }
}


import org.apache.poi.xwpf.usermodel.XWPFDocument
//  新格式 docx word 文档
def docx(file) {
    XWPFDocument doc;
    try {
        def data = [];
        doc = new XWPFDocument(new FileInputStream(file));
        doc.tablesIterator.each {tb ->
            tb.rows.each {row ->
                data << [
                        title: row.getCell(0).text.replace("\r", "").replace("\u0007", ""),
                        content: row.getCell(1).text.replace("\r", "</br>").replace("\u0007", "")
                ]
            }
        }
        return JSON.toJSONString([data: data])
    } catch(ex) {
        log.error ex
    } finally {
        doc?.close()
    }
}